using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
//using Microsoft.SharePoint.Portal.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Office.Server.Search;
using Microsoft.Office.Server.Search.Administration;
using IWCommunity.Common;


namespace IWCommunity.WebControls
{

    [ToolboxData("<{0}:EditProfileWebPart runat=server></{0}:EditProfileWebPart>")]
    [XmlRoot(Namespace = "IWCommunity.WebControls.WebParts")]
    public class EditProfileWebPart : Microsoft.SharePoint.WebPartPages.WebPart, INamingContainer
    {

        protected TextBox txtEmail;
        protected TextBox txtFirstName;
        protected TextBox txtLastName;
        protected TextBox txtCompany;
        protected TextBox txtJobTitle;
        protected TextBox txtTelephone;
        protected Button btnSubmit;
        protected Button btnCancel;
        protected Table editDetailsTable;


        /// <summary>
        /// set defaults in the constructor
        /// </summary>
        public EditProfileWebPart()
        {


        }

        #region Overriden Methods


        /// <summary>
        ///     Adds a field and label to the CreateUserWizard control
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="controlName"></param>
        /// <param name="requiredValuePrompt"></param>
        /// <returns></returns>
        private TableRow AddField(string prompt, Control ctrl, string requiredValuePrompt)
        {
            TableRow tr1 = new TableRow();
            TableCell td1 = new TableCell();
            TableCell td2 = new TableCell();
            Label lblPrompt = new Label();
            TextBox txtField = ctrl as TextBox;
            lblPrompt.Text = prompt;
            lblPrompt.AssociatedControlID = ctrl.ID;
            td1.Controls.Add(lblPrompt);
            td1.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(txtField);
            tr1.Cells.Add(td1);
            tr1.Cells.Add(td2);
            if (requiredValuePrompt != null)
            {
                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ControlToValidate = txtField.ID;
                rfv.ID = "rfv" + txtField.ID;
                rfv.ValidationGroup = this.ID;
                rfv.Text = requiredValuePrompt;
                rfv.EnableClientScript = true;
                td2.Controls.Add(rfv);
            }
            return tr1;
        }

        protected override void CreateChildControls()
        {
            //create search table
            editDetailsTable = new Table();
            editDetailsTable.ID = "editDetails";
            
            txtEmail = new TextBox();
            txtEmail.ID = "txtEmail";
            TableRow emailRow = AddField("Email:", txtEmail, "Email is required");
            editDetailsTable.Rows.Add(emailRow);


            txtFirstName = new TextBox();
            txtFirstName.ID = "txtFirstName";
            TableRow fNameRow = AddField("First Name:", txtFirstName, "First Name is required");
            editDetailsTable.Rows.Add(fNameRow);

            txtLastName = new TextBox();
            txtLastName.ID = "txtLastName";
            TableRow lNameRow = AddField("Last Name:", txtLastName, "Last Name is required");
            editDetailsTable.Rows.Add(lNameRow);

            txtCompany = new TextBox();
            txtCompany.ID = "txtCompany";
            TableRow companyRow = AddField("Company:", txtCompany, null);
            editDetailsTable.Rows.Add(companyRow);

            txtJobTitle = new TextBox();
            txtJobTitle.ID = "txtJobTitle";
            TableRow jobTitleRow = AddField("Job Title:", txtJobTitle, null);
            editDetailsTable.Rows.Add(jobTitleRow);

            txtTelephone = new TextBox();
            txtTelephone.ID = "txtTelephone";
            TableRow telRow = AddField("Telephone:", txtTelephone, null);
            editDetailsTable.Rows.Add(telRow);

            btnSubmit = new Button();
            btnSubmit.ID = "btnSave";
            btnSubmit.Text = "Save";
            btnSubmit.CausesValidation = true;
            btnSubmit.Click += new EventHandler(btnSubmit_Click);

            btnCancel = new Button();
            btnCancel.ID = "btnCancel";
            btnCancel.Text = "Cancel";
            btnCancel.Click += new EventHandler(btnCancel_Click);

            //row for buttons
            TableRow buttonsRow = new TableRow();
            
            //submit button
            TableCell buttons1Cell = new TableCell();
                    

            //cancel button
            TableCell buttons2Cell = new TableCell();
            buttons2Cell.HorizontalAlign = HorizontalAlign.Left;
            buttons2Cell.Controls.Add(btnSubmit);
            buttons2Cell.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            buttons2Cell.Controls.Add(btnCancel);

            buttonsRow.Cells.Add(buttons1Cell);
            buttonsRow.Cells.Add(buttons2Cell);

            editDetailsTable.Rows.Add(buttonsRow);

            this.Controls.Add(editDetailsTable);

            if (!Page.IsPostBack)
                LoadDefaultValues();
           
            base.CreateChildControls();
           
        }

        private void LoadDefaultValues()
        {
          
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser == null)
                return;

            string currentUserName = currentUser.UserName;
            txtEmail.Text = currentUser.Email;
            
            //get user profile
            ProfileBase userProfile = DefaultProfile.Create(currentUserName);
            try
            {
                if (userProfile["FirstName"] != null)
                    txtFirstName.Text = userProfile["FirstName"].ToString();

                if (userProfile["LastName"] != null)
                    txtLastName.Text = userProfile["LastName"].ToString();

                if (userProfile["Company"] != null)
                    txtCompany.Text = userProfile["Company"].ToString();

                if (userProfile["JobTitle"] != null)
                    txtJobTitle.Text = userProfile["JobTitle"].ToString();

                if (userProfile["Telephone"] != null)
                    txtTelephone.Text = userProfile["Telephone"].ToString();

            }
            catch (Exception ex)
            {
                Logger.LogError(ex,"Error in getting user profile information");
                this.Controls.Add(Utilities.CreateErrorMessage("Error in web part " + ex.Message));
                
            }
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Redirect("/"); //send to home page
        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            Page.Validate(); //should have to call this becuase button should call...but weird behaviour here...running out of time to check this

            if (!Page.IsValid)
                return;

            //attempt to save new values
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser == null)
                return;

            string currentUserName = currentUser.UserName;
            if (currentUser.Email.ToLower() != txtEmail.Text.ToLower())
            {
                currentUser.Email = txtEmail.Text.Trim();
                Membership.UpdateUser(currentUser); //update email if changed
            }
            
            //get user profile
            ProfileBase userProfile = DefaultProfile.Create(currentUserName);
            try
            {

                userProfile.SetPropertyValue("FirstName", txtFirstName.Text.Trim());
                userProfile.SetPropertyValue("LastName", txtLastName.Text.Trim());

                if (txtCompany.Text.Length > 0)
                    userProfile.SetPropertyValue("Company", txtCompany.Text.Trim());
                if (txtJobTitle.Text.Length > 0)
                    userProfile.SetPropertyValue("JobTitle", txtJobTitle.Text.Trim());
                if (txtTelephone.Text.Length > 0)
                    userProfile.SetPropertyValue("Telephone", txtTelephone.Text.Trim());

                userProfile.Save();

//                this.Controls.Add(new LiteralControl("<img src='/_layouts/images/kpinormallarge-0.gif' />"));
                this.Controls.Add(new LiteralControl("your details have been updated succesfully, use the navigation links on the top of the page to continue"));
                editDetailsTable.Visible = false;
                

            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error in saving user profile information");
                this.Controls.Add(Utilities.CreateErrorMessage("Error in web part " + ex.Message));

            }
        }




        #endregion





        #region Properties


        private bool _includeSiteScopes = true;
        [Browsable(true), Category("Miscellaneous"), WebPartStorage(Storage.Shared), FriendlyName("Include Site Scopes"), Description("Include site scopes in the scopes drop down list")]
        public bool IncludeSiteScopes
        {
            get
            {
                return _includeSiteScopes;
            }

            set
            {
                _includeSiteScopes = value;
            }
        }

        private bool _includeCtxScopes = true;
        [Browsable(true), Category("Miscellaneous"), DefaultValue(true), WebPartStorage(Storage.Shared), FriendlyName("Include Site Context Scopes"), Description("Include site context scopes in scopes drop down list")]
        public bool IncludeCtxScopes
        {
            get
            {
                return _includeCtxScopes;
            }

            set
            {
                _includeCtxScopes = value;
            }
        }

        private bool _showAdvancedSearch;
        [Browsable(true), Category("Miscellaneous"), DefaultValue(false), WebPartStorage(Storage.Shared), FriendlyName("Shows Advanced Page Link"), Description("Display Link to Advanced Search Page")]
        public bool ShowAdvancedSearch
        {
            get
            {
                return _showAdvancedSearch;
            }

            set
            {
                _showAdvancedSearch = value;
            }
        }

        private ScopeDisplayOptions _hideScopesList;
        [Browsable(true), Category("Miscellaneous"), DefaultValue(ScopeDisplayOptions.Always), WebPartStorage(Storage.Shared), FriendlyName("Display Scopes List"), Description("Display Scopes Drop Down List")]
        public ScopeDisplayOptions HideScopesList
        {
            get
            {
                return _hideScopesList;
            }

            set
            {
                _hideScopesList = value;
            }
        }

        private string _scopeGroup;
        [Browsable(true), Category("Miscellaneous"), DefaultValue("Search Dropdown"), WebPartStorage(Storage.Shared), FriendlyName("Scope Group"), Description("Default Scope Group")]
        public string ScopeGroup
        {
            get
            {
                return _scopeGroup;
            }

            set
            {
                _scopeGroup = value;
            }
        }

        private string _goImageUrl;
        [Browsable(true), Category("Miscellaneous"), DefaultValue("/_layouts/images/gosearch.gif"), WebPartStorage(Storage.Shared), FriendlyName("Go Image Url"), Description("Go Button's Image Url")]
        public string GoImageUrl
        {
            get
            {
                return _goImageUrl;
            }

            set
            {
                _goImageUrl = value;
            }
        }

        private string _AdvImageUrl;
        [Browsable(true), Category("Miscellaneous"), DefaultValue(""), WebPartStorage(Storage.Shared), FriendlyName("Advanced Search Image Url"), Description("Advanced search button's Image Url")]
        public string AdvancedImageUrl
        {
            get
            {
                return _AdvImageUrl;
            }

            set
            {
                _AdvImageUrl = value;
            }
        }


        private string _advancedSearchUrl;
        [Browsable(true), Category("Miscellaneous"), DefaultValue("advanced.aspx"), WebPartStorage(Storage.Shared), FriendlyName("Advanced Search Page Url"), Description("Advanced Search Page Url")]
        public string AdvancedSearchUrl
        {
            get
            {
                return _advancedSearchUrl;
            }

            set
            {
                _advancedSearchUrl = value;
            }
        }

        private string _resultsPageUrl;
        [Browsable(true), Category("Miscellaneous"), DefaultValue("results.aspx"), WebPartStorage(Storage.Shared), FriendlyName("Search Results Page Url"), Description("Search Results Page Url")]
        public string ResultsPageUrl
        {
            get
            {
                return _resultsPageUrl;
            }

            set
            {
                _resultsPageUrl = value;
            }
        }

        private Int32 _textBoxWidth = 0;
        [Browsable(true), Category("Miscellaneous"), DefaultValue(170), WebPartStorage(Storage.Shared), FriendlyName("Text Box Width"), Description("Width of the Search Text Box")]
        public Int32 TextBoxWidth
        {
            get
            {
                return _textBoxWidth;
            }

            set
            {
                _textBoxWidth = value;
            }
        }









        #endregion

    }


  
}
